import logUtil from '@/utils/logUtil'
import { Middleware } from 'koa'

export enum RespCode {
  SUCCESS = 200,
  SERVER_ERROR = 500,
}

export interface Response {
  code: RespCode
  data?: any
  msg: any
}

export type SuccessFun = (data?: any, msg?: any, code?: RespCode) => void
export type FailFun = (msg?: any, code?: RespCode) => void

const respUtilMid: Middleware = async (ctx, next) => {
  ctx.success = (data = undefined, msg = 'success', code = RespCode.SUCCESS) => {
    ctx.body = { code, data, msg }
  }

  ctx.fail = (msg = '', code = RespCode.SERVER_ERROR) => {
    const resp = { code, msg }
    logUtil.error(resp)
    ctx.body = resp
  }

  await next()
}

export default respUtilMid
